<template>
  <div class="autumn-container">
    <!-- 面包 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>我的待办</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="autumn-center">
      <!-- 搜索栏 -->
      <div class="query-form">
        <autumn-search :modelValue="queryInfo" @search="search" @reset="resetSearch">
          <template #default>
            <el-form-item prop="processInsName" label="审核事项">
              <el-input v-model="queryInfo.processInsName" />
            </el-form-item>
            <el-form-item prop="name" label="审核节点">
              <el-input v-model="queryInfo.name" />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker v-model="startEndTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </template>
        </autumn-search>
      </div>

      <!-- 数据表格 -->
      <div class="main-body top">
        <autumn-table ref="mainTableRef" :page="page" @changePage="changePage" @changeSelect="changeSelect">
          <template #button>
            <el-button icon="el-icon-refresh-right" :disabled="selectNum !== 1" @click="toTransform('1')">转办
            </el-button>
            <el-button type="success" icon="el-icon-avatar" :disabled="selectNum !== 1" @click="toDelegate('2')">委托
            </el-button>
            <el-button type="warning" icon="el-icon-check" :disabled="selectNum !== 1" @click="claim">签收
            </el-button>
            <el-button type="danger" icon="el-icon-close" :disabled="selectNum !== 1" @click="cancelClaim">
              取消</el-button>
          </template>
          <template #column>
            <el-table-column type="selection" fixed="left" align="center" />
            <el-table-column prop="processInsName" label="审核事项" />
            <el-table-column prop="name" label="审核节点" width="150" />
            <el-table-column label="签收" width="80" align="center">
              <template #default="scope">
                <el-tag size="small" type="success" v-if="scope.row.assignee">已签收</el-tag>
                <el-tag size="small" type="info" v-else>未签收</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="开始时间" width="150" align="center"
              :formatter="(row: any) => $moment(row.createTime, 'YYYY-MM-DD HH:mm')" />
            <el-table-column prop="dueDate" label="任务期限" width="150" align="center" />
            <el-table-column prop="description" label="备注" />
            <el-table-column label="操作" fixed="right" width="150" align="center">
              <template #default="scope">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-document-checked" size="small" title="审核"
                    v-if="$hasPermission('flow:task:complete')" @click="toAudit(scope.row)"></el-button>
                  <el-button type="info" icon="el-icon-view" size="small" title="查看" @click="toView(scope.row)" />
                  <el-button type="info" icon="el-icon-tickets" size="small" title="表单" v-if="scope.row.formKey"
                    @click="toForm(scope.row)" />
                </el-button-group>
              </template>
            </el-table-column>
          </template>
        </autumn-table>
      </div>
    </div>

    <!-- 审核弹窗 -->
    <audit-component ref="auditRef" @apply="submitAudit" />

    <!-- 审核人弹窗 -->
    <assignee-component ref="assigneeRef" @apply="changeAssignee" />

    <!-- 查看弹窗 -->
    <view-task ref="viewTaskRef" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import AuditComponent from '../../component/AuditComponent.vue'
import AssigneeComponent from '../../component/AssigneeComponent.vue'
import ViewTask from '../../component/ViewTask.vue'
import { pageUndoeTask, transformTask, delegateTask, claimTask, cancelClaimTask } from 'src/api/flow/activiti'
import useTable from 'src/hooks/useTable'
import { $moment, $confirmMsg, $hasPermission } from 'src/hooks/useCommon'

const { page, selectNum, changeSelect } = useTable()
const router = useRouter()

// 分页查询
const mainTableRef = ref()
const queryInfo = reactive({
  processInsName: '',
  name: '',
  startTime: '',
  endTime: ''
})
const changePage = function (pageNumber: number, pageSize: number) {
  page.pageNumber = pageNumber
  page.pageSize = pageSize
  pageUndoeTask({ ...queryInfo, pageNumber, pageSize }).then(({ data }) => {
    page.data = data.list
    page.total = data.total
  })
}
const search = function () {
  changePage(1, 10)
}
search()

const action = ref<string>('')

const startEndTime = ref([])
watch(startEndTime, (newVal) => {
  if (!newVal || newVal.length === 0) {
    queryInfo.startTime = ''
    queryInfo.endTime = ''
    return
  }
  queryInfo.startTime = $moment(newVal[0])
  queryInfo.endTime = $moment(newVal[1])
})

const resetSearch = () => {
  startEndTime.value = []
  queryInfo.startTime = ''
  queryInfo.endTime = ''
}

// 查看流程历史
const viewTaskRef = ref()
const toView = (row: any) => {
  viewTaskRef.value.open(row.processInsId)
}

// 查看表单
const toForm = (row: any) => {
  const { id: taskId, businessKey, processInsId, formKey } = row
  router.push({
    path: formKey,
    query: {
      method: 'view',
      taskId,
      businessKey,
      processInsId
    }
  })
}

// 审核
const auditRef = ref()
const toAudit = (row: any) => {
  const { id: taskId, businessKey, processInsId, formKey } = row
  if (!formKey) {
    auditRef.value.open({
      taskId,
      businessKey,
      processInsId
    })
    return
  }
  router.push({
    path: formKey,
    query: {
      method: 'audit',
      taskId,
      businessKey,
      processInsId
    }
  })
}
const submitAudit = () => {
  search()
}

// 签收、取消签收
const claim = () => {
  const selection = mainTableRef.value.$refs.dataTableRef.getSelectionRows()
  const row = selection[0]
  if (row.assignee) {
    ElMessage.error('该待办事项已签收')
    return
  }
  $confirmMsg('确认签收该任务吗？', () => {
    claimTask(row.id).then(() => {
      search()
    })
  })
}
const cancelClaim = () => {
  const selection = mainTableRef.value.$refs.dataTableRef.getSelectionRows()
  const row = selection[0]
  if (!row.assignee) {
    ElMessage.error('该待办事项已取消签收')
    return
  }
  $confirmMsg('确认取消签收该任务吗？', () => {
    cancelClaimTask(row.id).then(data => {
      search()
    })
  })
}

// 转办、委托
const assigneeRef = ref()
const toTransform = (val: string) => {
  action.value = val
  assigneeRef.value.open()
}
const toDelegate = (val: string) => {
  action.value = val
  assigneeRef.value.open()
}
const changeAssignee = (rows: Array<any>) => {
  const selection = mainTableRef.value.$refs.dataTableRef.getSelectionRows()
  const row = selection[0]
  if (action.value === '1') { // 转办
    $confirmMsg(`确认转交【${rows[0].name}】办理吗？`, () => {
      transformTask({ id: row.id, assignee: rows[0].loginName }).then(data => {
        search()
      })
    })
  } else if (action.value === '2') { // 委托
    $confirmMsg(`确认委托【${rows[0].name}】办理吗？`, () => {
      delegateTask({ id: row.id, assignee: rows[0].loginName }).then(data => {
        search()
      })
    })
  }
}
</script>

<style lang="scss" scoped>
</style>
